package com.rem.zookeeper.connect;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * 连接zookeeper
 *
 * @author Rem
 * @date 2021-06-22
 */

public class ZookeeperConnect {

    public static void main(String[] args) throws Exception {
        // 计数器对象
        CountDownLatch countDownLatch = new CountDownLatch(1);
        /**
         * 形参:
         * connectString -逗号分隔的主机: 端口对，每个端口对对应一个zk服务器
         * sessionTimeout -以毫秒为单位的会话超时
         * watcher -状态变化会被通知的watcher对象，也可能会被通知节点事件
         */
        ZooKeeper zooKeeper = new ZooKeeper("localhost:2191,localhost:2192,localhost:2193", 5000, event -> {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                System.err.println("连接创建成功!");
                countDownLatch.countDown();
            }
        });

        // 主线程阻塞等待连接对象的创建成功
        countDownLatch.await();
        // 会话编号
        System.out.println(zooKeeper.getSessionId());
        zooKeeper.close();
    }
}
